<template>
	<view class="container">
		<view class="bg-white padding-sm" @click="
        toPage(
          '/filePage/pages/service-outlets/service-outlets?service_id=' + service_id
        )
      ">
			<view class="text-13 text-333 text-bold"> 选择服务网点 </view>
			<view class="flex justify-between align-center" style="margin-top: 46rpx">
				<view v-if="service_id" class="flex justify-start align-center" style="max-width: 90vw">
					<image :src="service.logo" mode="" class="cu-avatar round"></image>
					<view class="margin-left" style="width: calc(100% - 104rpx)">
						<view class="text-15 text-333">
							{{ service.shopName }}
						</view>
						<view class="text-cut margin-top-sm text-sm text-666">
							{{ service.address }}
						</view>
					</view>
				</view>
				<view v-else class="flex justify-start align-center" style="max-width: 90vw">
					请选择服务网点
				</view>
				<image :src="baseUrl + '/static/right.png'" mode="" style="width: 22rpx; height: 22rpx"></image>
			</view>
		</view>
		<view class="bg-white margin-top-sm">
			<view class="solid-bottom text-13 flex justify-between align-center padding">
				<view class="text-333 text-bold"> 选择订单类型 </view>
				<radio-group class="flex-treble flex justify-around align-center margin-left-xs" @change="RadioChange">
					<view class="flex justify-start align-center">
						<radio class="radio yellow" :class="radio == '1' ? 'bg-white' : ''"
							:checked="radio == '1' ? true : false" value="1"></radio>
						<view class="title text-13 margin-left-xs">普通订单</view>
					</view>
					<view class="flex justify-start align-center">
						<radio class="radio yellow" :class="radio == '3' ? 'checked' : ''"
							:checked="radio == '3' ? true : false" value="3"></radio>
						<view class="title text-13 margin-left-xs">竞标订单</view>
					</view>
				</radio-group>
			</view>
			<view class="text-13 flex justify-between align-center padding">
				<view class="text-333 text-bold"> 选择服务分类 </view>
				<view class="flex justify-start align-center" @click="changeAddress2">
					<view class="text-767696 margin-right-xs">
						{{ sysCategoryName }}
					</view>
					<image :src="baseUrl + '/static/right.png'" mode="" style="width: 22rpx; height: 22rpx">
					</image>
				</view>
			</view>
		</view>
		<view class="bg-white margin-top-sm">
			<view class="solid-bottom text-13 flex justify-between align-center padding">
				<view class="text-333 flex-sub text-bold"> 联系人 </view>
				<input type="text" v-model="userName" value="" class="text-13 flex-treble" placeholder="请填写联系人姓名" />
			</view>
			<view class="solid-bottom text-13 flex justify-between align-center padding">
				<view class="text-333 flex-sub text-bold"> 联系电话 </view>
				<input type="number" v-model="mobile" value="" class="text-13 flex-treble" placeholder="请填写联系电话" />
			</view>
			<view class="text-13 flex justify-between align-center padding solid-bottom">
				<view class="text-333 text-bold"> 施工地址 </view>
				<view class="flex justify-start align-center" @click="changeAddress">
					<view class="text-767696 margin-right-xs">
						{{ address }}
					</view>
					<image :src="baseUrl + '/static/right.png'" mode="" style="width: 22rpx; height: 22rpx">
					</image>
				</view>
			</view>
			<view class="solid-bottom text-13 flex justify-between align-center padding">
				<view class="text-333 flex-sub text-bold"> 详细地址 </view>
				<input type="text" value="" v-model="detailedAddress" class="text-13 flex-treble"
					placeholder="详细地址，例1号楼1层1001室" />
			</view>
		</view>
		<view class="bg-white margin-top-sm">
			<view class="solid-bottom text-13 flex justify-between align-center padding">
				<view class="text-333 flex-sub text-bold"> 预估价格 </view>
				<input type="digit" value="" v-model="price" class="f-grow1 margin-left-sm" />
				<view class="color"> 元 </view>
			</view>
			<view class="text-13 flex justify-between align-center padding" v-if="service_id && WorkerList.length > 0">
				<view class="text-333 text-bold"> 提醒技工 </view>
				<view class="flex justify-start align-center" @click="showModal">
					<view class="text-767696 margin-right-xs">
						{{ remandUserName }}
					</view>
					<image :src="baseUrl + '/static/right.png'" mode="" style="width: 22rpx; height: 22rpx">
					</image>
				</view>
			</view>
			<view class="solid-bottom text-13 flex justify-between align-center padding">
				<view class="text-333 flex-sub text-bold"> 详细描述 </view>
				<input type="text" value="" v-model="desc" class="text-13 flex-treble" placeholder="在这里描述下您的需求" />
			</view>
			<view class="cu-form-group padding-top">
				<view class="grid col-3 grid-square flex-sub">
					<view class="bg-img" v-for="(item, index) in picList" :key="index">
						<image :src="item" mode="aspectFill"></image>
						<view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
							<text class="cuIcon-close"></text>
						</view>
					</view>
					<view class="solids" @tap="ChooseImage">
						<text class="cuIcon-cameraadd"></text>
					</view>
				</view>
			</view>
			<view v-if='!show' class="solid-bottom text-13 flex justify-between align-center padding">
				<view class="text-333 text-bold"> 支付方式 </view>
				<radio-group class="flex-treble flex justify-around align-center margin-left-xs" @change="RadioChange2">
					<view class="flex justify-start align-center">
						<radio class="radio yellow" :class="payType == 'A' ? 'bg-white' : ''"
							:checked="payType == 'A' ? true : false" value="A"></radio>
						<view class="title text-13 margin-left-xs">微信支付</view>
					</view>
					<view class="flex justify-start align-center">
						<radio class="radio yellow" :class="payType == 'B' ? 'checked' : ''"
							:checked="payType == 'B' ? true : false" value="B"></radio>
						<view class="title text-13 margin-left-xs">账户余额支付</view>
					</view>
				</radio-group>
			</view>
		</view>
		<view class="flex justify-start align-center padding text-sm">
			<view class="flex justify-start align-center" @click="changeType">
				<image v-if="is_agree" :src="baseUrl + '/static/selected.png'" mode=""
					style="width: 26rpx; height: 26rpx"></image>
				<image v-else :src="baseUrl + '/static/unselected.png'" mode="" style="width: 26rpx; height: 26rpx">
				</image>
				<text class="text-333 margin-left-xs">同意并认真阅读</text>
			</view>
			<text class="color"
				@click="toPage('/filePage/pages/protocol/protocol?title=佐佑帮信息发布协议&code=PROTOCOL_INFO_PUBLISH&type=4')">《佐佑帮信息发布协议》</text>
		</view>
		<view class="" style="padding: 48rpx 20rpx">
			<button @click="submit" class="bg-color text-15 padding radius10 text-center text-white">
				确认发布
			</button>
		</view>

		<!-- <w-picker
		        :visible="visible"
		        mode="region"
		        value="['100','10010','1001010']"
		        default-type="value"
		        :hide-area="false"
		        @confirm="onConfirm($event)"
		        @cancel="changeAddress"
		        ref="region" 
		    ></w-picker> -->
		<w-picker :visible="visible2" mode="linkage" :value="[]" :options="options" :level="2" default-type="id"
			:default-props="defaultProps1" @confirm="onConfirm2($event)" @cancel="changeAddress2" ref="linkage">
		</w-picker>
		<view class="cu-modal bottom-modal" :class="modalName == 'bottomModal' ? 'show' : ''" @click="hideModal()">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-between">
					<view class="action text-green"></view>
					<view class="text-221815 text-17"> 选择技工 </view>
					<view class="action text-blue" @tap="hideModal">取消</view>
				</view>
				<scroll-view scroll-y="true" style="height: 200rpx">
					<view class="flex justify-between align-center padding solid-bottom" v-for="item in WorkerList"
						@click="cheacked(item)">
						<view class="flex justify-between align-center f-grow1">
							<view class="text-xl text-221815">
								{{ item.username }}
							</view>
							<view class="text-sm text-999">
								{{ item.worktype }}
							</view>
						</view>
						<image v-if="remandUserId == item.id" :src="baseUrl + '/static/selected.png'" mode=""
							class="margin-left margin-right-sm" style="width: 26rpx; height: 26rpx"></image>
						<image v-else :src="baseUrl + '/static/unselected.png'" mode=""
							class="margin-left margin-right-sm" style="width: 26rpx; height: 26rpx"></image>
					</view>
				</scroll-view>
			</view>
		</view>
		<passkeyborad :money='money' @message='message' @close='close' :show="show"></passkeyborad>
	</view>
</template>

<script>
	import passkeyborad from '@/components/yzc-paykeyboard/yzc-paykeyboard.vue'
	export default {
		data() {
			return {
				baseUrl: this.$config.baseUrl,
				picList: [],
				service_id: "",
				service: {},
				radio: "1",
				visible: false,
				mobile: "",
				userName: "",
				detailedAddress: "",
				address: "请选择",
				addressCode: "",
				desc: "",
				price: "",
				visible2: false,
				defaultProps1: {
					label: "name",
					value: "id",
					children: "children",
				},
				options: [],
				WorkerList: [],
				modalName: null,
				remandUserId: "",
				remandUserName: "请选择",
				sysCategoryId: "",
				sysCategoryName: "请选择",
				is_agree: false,
				addressLatitude: "",
				addressLongitude: "",
				payType: 'A',
				show: false,
				password: 0,
				money: 0,
				serviceType: '',
				orderNo: ''
			};
		},
		components: {
			passkeyborad
		},
		onLoad(options) {
			if (options.sysCategoryId) this.sysCategoryId = options.sysCategoryId
			if (options.sysCategoryName) this.sysCategoryName = options.sysCategoryName
		},
		onShow() {
			let that = this;
			uni.getStorage({
				key: "service_id",
				success(res) {
					that.service_id = res.data;
					that.getService();
					that.getWorkerList();
					console.log(res)
				},
			});
			this.getTreeList();
		},
		methods: {

			async ChooseImage() {
				let that = this
				uni.chooseImage({
					sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ["album"], //从相册选择
					success: (res) => {
						// console.log(res);
						res.tempFilePaths.forEach(item => {
							that.$upload(item).catch((req) => {
								// console.log(req);
								that.picList.push(req.data);
							});
						})

					},
				});
			},
			DelImg(e) {
				uni.showModal({
					title: "提示",
					content: "确定要删除吗？",
					cancelText: "取消",
					confirmText: "确定",
					success: (res) => {
						if (res.confirm) {
							this.picList.splice(e.currentTarget.dataset.index, 1);
						}
					},
				});
			},
			toPage(url) {
				this.$util.openNewPage(url);
			},
			async getService() {
				const [err, res] = await this.$get(this.$api.shop_detail, {
					id: this.service_id,
				});
				if (res) {
					this.service = res.data;
					// console.log(res)
				}
			},
			RadioChange(e) {
				this.radio = e.detail.value;
			},
			RadioChange2(e) {
				this.payType = e.detail.value;
			},
			changeAddress() {
				let that = this;
				// #ifdef  APP-PLUS
				uni.navigateTo({
					url: "/pagesA/pages/chooseLocation/chooseLocation?verified=1",
					animationType: "slide-in-bottom",
				})
				// #endif
				// #ifdef  MP-WEIXIN
				uni.chooseLocation({
					success: function(res) {
						// console.log('位置名称：' + res.name);
						// console.log('详细地址：' + res.address);
						// console.log('纬度：' + res.latitude);
						// console.log('经度：' + res.longitude);
						that.address = res.address;
						that.addressLongitude = res.longitude;
						that.addressLatitude = res.latitude;
						that.detailedAddress = res.name;
					},
				});
				// #endif
			},
			changeAddress2() {
				this.visible2 = !this.visible2;
			},
			onConfirm(e) {
				this.addressCode = e.value;
				this.address = e.result;
				console.log(e);
			},
			async getTreeList() {
				const [err, res] = await this.$get(this.$api.home_categoryTreeList, {
					type: 2,
				});
				if (res) {
					this.options = res.data;
					console.log(res);
				}
			},
			onConfirm2(e) {
				this.changeAddress2();
				this.sysCategoryId = e.value[1];
				this.sysCategoryName = e.obj.col2.name;

				// console.log(e)
			},
			async getWorkerList() {
				const [err, res] = await this.$get(this.$api.shop_shopWorkerList, {
					shopId: this.service_id,
					pageNum: 1,
					pageSize: 100,
				});
				if (res) {
					this.WorkerList = res.data.list;
					// console.log(res)
				}
			},
			showModal() {
				this.modalName = "bottomModal";
			},
			hideModal() {
				this.modalName = null;
			},
			cheacked(e) {
				this.hideModal();
				this.remandUserId = e.id;
				this.remandUserName = e.username;
			},
			async submit() {
				if (!this.is_agree) {
					this.$util.msg("未同意发布协议");
					return;
				}
				if (!this.service_id) {
					return this.$util.msg('请选择服务网点')
				}
				if (!this.sysCategoryId) {
					return this.$util.msg('选择服务分类')
				}
				if (!this.userName) {
					return this.$util.msg('联系人姓名不能为空')
				}
				if (!this.mobile) {
					return this.$util.msg('联系电话不能为空')
				}

				if (!this.addressLatitude) {
					return this.$util.msg('施工地址不能为空')
				}
				if (!this.detailedAddress) {
					return this.$util.msg('详细地址不能为空')
				}

				if (!this.price) {
					return this.$util.msg('预估金额不能为空')
				} else {
					this.money = Number(this.price)
				}
				if (!this.desc) {
					return this.$util.msg('描述不能为空')
				}
				if (this.picList.length == 0) {
					return this.$util.msg('图片不能为空')
				}
				// if (
				// 	!this.service_id ||
				// 	!this.mobile ||
				// 	!this.userName ||
				// 	!this.addressLatitude ||
				// 	!this.desc ||
				// 	!this.detailedAddress ||
				// 	this.picList.length == 0 ||
				// 	!this.price ||
				// 	!this.sysCategoryId
				// ) {
				// 	this.$util.msg("请完善信息");
				// 	return;
				// }
				uni.showLoading({
					title: '正在发布',
					mask: true
				});
				// this.money =this.price
				// console.log(this.money)
				const [err, res] = await this.$post(this.$api.home_addOrderService, {
					shopId: this.service_id,
					mobile: this.mobile,
					serviceType: this.radio,
					userName: this.userName,
					addressLatitude: this.addressLatitude,
					addressLongitude: this.addressLongitude,
					desc: this.desc,
					detailedAddress: this.detailedAddress,
					picList: this.picList,
					price: Number(this.price) * 100,
					remandUserId: this.remandUserId,
					sysCategoryId: this.sysCategoryId,
				});
				if (res) {
					console.log(res);
					// this.$util.msg(res.message);
					this.orderNo = res.data.orderNo
					this.serviceType = res.data.serviceType


					// #ifdef  MP-WEIXIN
					const data = {
						orderNo: res.data.orderNo,
						orderType: res.data.serviceType,
						payWay: 1,
						appId: this.$config.wxAppId,
						openId: uni.getStorageSync('openid')

					};
					// #endif


					// #ifdef  APP-PLUS
					const data = {
						orderNo: res.data.orderNo,
						orderType: res.data.serviceType,
						payWay: 2,
						appId: this.$config.appId,
						openId: uni.getStorageSync('openid')
					};
					// #endif

					console.log(data)

					if (this.payType == 'A') {
						const [error, rs] = await this.$get(this.$api.weixinPay, data);
						console.log(error, rs)
						if (rs) {
							console.log(rs);
							const data = rs.data;
							uni.hideLoading();
							// #ifdef  MP-WEIXIN
							uni.requestPayment({
								provider: "wxpay",
								appId: data.appId,
								timeStamp: data.timeStamp,
								nonceStr: data.nonceStr,
								package: data._package,
								signType: data.signType,
								paySign: data.paySign,
								success: function(res) {
									console.log("success:" + JSON.stringify(res));

									setTimeout(() => {
										uni.navigateBack()
									}, 1500)
								},
								fail: function(err) {
									console.log("fail:" + JSON.stringify(err));
								},
							});
							// #endif

							// #ifdef  APP-PLUS
							console.log(111)
							uni.requestPayment({
								"provider": "wxpay",
								"orderInfo": {
									"appid": data.appId, // 微信开放平台 - 应用 - AppId，注意和微信小程序、公众号 AppId 可能不一致
									"noncestr": data.nonceStr, // 随机字符串
									"package": data._package, // 固定值
									"partnerid": data.partnerid, // 微信支付商户号
									"prepayid": data.prepayid, // 统一下单订单号 
									"timestamp": data.timeStamp, // 时间戳（单位：秒）
									"sign": data.sign // 签名，这里用的 MD5 签名
								},
								success(res) {
									setTimeout(() => {
										uni.navigateBack()
									}, 1500)
								},
								fail(e) {
									console.log(e)
								}
							})
							// #endif
						}
					} else {
						this.money = Number(this.price * 100)
						console.log(this.price)
						console.log(this.money)
						this.show = true

						uni.hideLoading()
						// const [error, res] = await this.$get(this.$api.orderService_accountPay, data);
						// if (res) {
						// 	// console.log(res);
						// 	this.$util.msg(res.message)
						// 	uni.hideLoading();
						// 	setTimeout(() => {
						// 		uni.navigateBack()
						// 	}, 1500)
						// }
					}



					// console.log(res)
				}
			},
			changeType() {
				this.is_agree = !this.is_agree;
			},
			close() {
				// console.log(111111)
				this.show = false
			},
			message(password) {
				// console.log(password)
				var CusBase64 = require('@/common/js/base64.js');
				//函数调用
				var passWord = CusBase64.CusBASE64.encoder(password);
				this.$get(this.$api.verifyPayPassWord, {
					passWord,
					userId: uni.getStorageSync('userId')
				}).then(res => {
					const [err, rs] = res
					if (rs) {
						const data = {
							orderNo: this.orderNo,
							orderType: this.serviceType
						};
						this.$get(this.$api.orderService_accountPay, data).then(result => {
							const [err, rs] = result
							console.log('````````````')
							if (rs) {
								this.$util.msg(rs.message)
								this.show = false
								setTimeout(() => {
									uni.navigateBack()
								}, 1500)
							}
						})

					}
					if (err) {
						console.log('*******')
						this.show = false
						if (err.message == '请去设置密码！') {
							setTimeout(() => {
								uni.navigateTo({
									url: '/pagesA/pages/setPassword/setPassword'
								})
							}, 1500)
						}
					}
				})

			},
		},
	};
</script>

<style lang="scss" scoped>
	radio.radio[checked]::after,
	radio.radio .uni-radio-input-checked::after {
		z-index: 1;
	}
</style>
